/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultarAtletas.java
 *
 * Created on 02/05/2011, 00:46:11
 */
package Interface;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import ludi.Atleta;
import ludi.Curso;
import ludi.Usuario;
import utils.BancoDeDados;

/**
 *
 * @author alison
 */
public class ConsultarAtletas extends javax.swing.JInternalFrame {

    BancoDeDados banco;
    Usuario usuario;
    ArrayList<String> listaDeCursos;
    /** Creates new form ConsultarAtletas */
    public ConsultarAtletas(BancoDeDados banco, Usuario usuario) {
        try {
            this.banco = banco;
            this.usuario = usuario;
            this.listaDeCursos = banco.getListaDeCursos();
            if (usuario.getPermissoes() == 2){
                int i = 0;
                Curso curso = banco.getCurso(usuario.getLogin());
                while (i < listaDeCursos.size()){
                    if (!(banco.getCurso(listaDeCursos.get(i)).getUnidade().equals(curso.getUnidade()))){
                        listaDeCursos.remove(i);
                    } else{
                        i++;
                    }
                }
            }
            initComponents();
            updateTabelaAtletas();
            setVisible(true);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollTabelaAtletas = new javax.swing.JScrollPane();
        tabelaAtletas = new javax.swing.JTable();
        campoBusca = new javax.swing.JTextField();
        botaoPesquisar = new javax.swing.JButton();
        botaoGerenciar = new javax.swing.JButton();
        botaoCancelar = new javax.swing.JButton();
        seletorBuscar = new javax.swing.JComboBox();
        seletorCurso = new javax.swing.JComboBox();
        labelSelecione = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setTitle("Consultar Atletas");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameActivated(evt);
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        tabelaAtletas.setAutoCreateRowSorter(true);
        tabelaAtletas.setBackground(new java.awt.Color(254, 254, 254));
        try {
            tabelaAtletas.setModel(modeloTabelaAtletas(getListaDeTodosAtletas()));
        } catch (SQLException ex){
            ex.printStackTrace();
        }
        tabelaAtletas.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        scrollTabelaAtletas.setViewportView(tabelaAtletas);

        campoBusca.setText("Pesquisar atleta");
        campoBusca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                campoBuscaActionPerformed(evt);
            }
        });
        campoBusca.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                campoBuscaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoBuscaFocusLost(evt);
            }
        });

        botaoPesquisar.setText("Pesquisar");
        botaoPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoPesquisarActionPerformed(evt);
            }
        });

        botaoGerenciar.setText("Gerenciar Atleta Selecionado");
        botaoGerenciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoGerenciarActionPerformed(evt);
            }
        });

        botaoCancelar.setText("Cancelar");
        botaoCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarActionPerformed(evt);
            }
        });

        seletorBuscar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Nome", "Matrícula", "RG" }));

        ArrayList<String> nomesDosCursos = new ArrayList<String>(0);

        try {
            String todos = (usuario.getPermissoes() == 1) ? "Todos" : "Todos - " + banco.getCurso(usuario.getLogin()).getUnidade();
            nomesDosCursos.add(todos);
            for (int i = 0; i < listaDeCursos.size(); i++){
                Curso curso = banco.getCurso(listaDeCursos.get(i));
                nomesDosCursos.add(curso.getNome() + " - " + curso.getLogin());
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        seletorCurso.setModel(new javax.swing.DefaultComboBoxModel(nomesDosCursos.toArray()));
        seletorCurso.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                seletorCursoActionPerformed(evt);
            }
        });

        labelSelecione.setText("Selecione um curso:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(seletorCurso, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 106, Short.MAX_VALUE)
                        .addComponent(campoBusca, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(seletorBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoPesquisar))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(botaoCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(botaoGerenciar))
                    .addComponent(scrollTabelaAtletas, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 775, Short.MAX_VALUE)
                    .addComponent(labelSelecione))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelSelecione)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(seletorCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(seletorBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(botaoPesquisar)
                    .addComponent(campoBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(scrollTabelaAtletas, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoGerenciar)
                    .addComponent(botaoCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_botaoCancelarActionPerformed

    private void campoBuscaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_campoBuscaFocusGained
        campoBusca.setText("");
    }//GEN-LAST:event_campoBuscaFocusGained

    private void campoBuscaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_campoBuscaFocusLost
        if (campoBusca.getText().equals("")){
            campoBusca.setText("Pesquisar atleta");
            updateTabelaAtletas();
        }
    }//GEN-LAST:event_campoBuscaFocusLost

    private void seletorCursoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seletorCursoActionPerformed
        campoBusca.setText("Pesquisar atleta");
        updateTabelaAtletas();
    }//GEN-LAST:event_seletorCursoActionPerformed

    private void campoBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_campoBuscaActionPerformed
        updateTabelaAtletas();
    }//GEN-LAST:event_campoBuscaActionPerformed

    private void botaoPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoPesquisarActionPerformed
        updateTabelaAtletas();
    }//GEN-LAST:event_botaoPesquisarActionPerformed

    private void botaoGerenciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoGerenciarActionPerformed
        if (tabelaAtletas.getSelectedRow() < 0){
            JOptionPane.showMessageDialog(this, "Selecione um atleta!", "Consultar Atletas", JOptionPane.INFORMATION_MESSAGE);
        } else {
            String coluna;
            int i = -1;
            do {
                i++;
                coluna = tabelaAtletas.getColumnName(i);
            } while (!(coluna.equals("ID")));

           CriarAtleta frame;
            try {
                Atleta atleta = banco.getAtleta((Integer) tabelaAtletas.getValueAt(tabelaAtletas.getSelectedRow(), i));
                if ((usuario.getPermissoes() == 2) && (!atleta.getCurso().equals(usuario.getLogin()))){
                    JOptionPane.showMessageDialog(this, "Você não pode gerenciar atletas de outros cursos!", "Consultar Atleta", JOptionPane.ERROR_MESSAGE);
                } else{
                    frame = new CriarAtleta(banco, usuario, atleta);
                    frame.setVisible(true);
                    this.getDesktopPane().add(frame);
                    try {
                        frame.setSelected(true);
                    } catch (java.beans.PropertyVetoException e) {}
                }
            } catch (SQLException ex) {
                Logger.getLogger(ConsultarUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_botaoGerenciarActionPerformed

    private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameActivated
        updateTabelaAtletas();
    }//GEN-LAST:event_formInternalFrameActivated

    private DefaultTableModel modeloTabelaAtletas(ArrayList<Integer> listaDeAtletas){
        String[][] dados = new String [0][];
        String[] colunas = new String [] {"ID", "Nome", "Matrícula", "RG", "Gênero", "Curso"};

        DefaultTableModel modelo = new DefaultTableModel(dados, colunas){
             Class[] types = new Class [] {
                 java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
             };
             boolean[] canEdit = new boolean [] {
                 false, false, false, false, false, false
             };

             @Override
             public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
             }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };

        for (int i = 0; i < listaDeAtletas.size(); i++){
            try {
                Atleta atleta = banco.getAtleta(listaDeAtletas.get(i));
                String genero = (atleta.getGenero() == 1)? "Masculino" : "Feminino";

                modelo.addRow(new Object [] {atleta.getId(), atleta.getNome(), atleta.getMatricula(), atleta.getRg(), genero, atleta.getCurso()});
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        return modelo;
    }

    private ArrayList<Integer> getListaDeTodosAtletas(ArrayList<Integer> listaDeAtletas) throws SQLException{
        if (usuario.getPermissoes() == 2){
            int i = 0;
            Curso curso = banco.getCurso(usuario.getLogin());
            while (i < listaDeAtletas.size()){
                if (!(banco.getCurso(banco.getAtleta(listaDeAtletas.get(i)).getCurso()).getUnidade().equals(curso.getUnidade()))){
                    listaDeAtletas.remove(i);
                } else{
                    i++;
                }
            }
        }

        return listaDeAtletas;
    }

    private ArrayList<Integer> getListaDeTodosAtletas() throws SQLException{
        return getListaDeTodosAtletas(banco.getListaDeAtletas(null, null));
    }

    private void updateTabelaAtletas(){
        ArrayList<Integer> listaDeAtletas = null;
        try {
            if (seletorCurso.getSelectedIndex() == 0){
                if (campoBusca.getText().equals("Pesquisar atleta")){
                    listaDeAtletas = getListaDeTodosAtletas();
                } else {
                    if (seletorBuscar.getSelectedItem().toString().equals("Nome")){
                        listaDeAtletas = getListaDeTodosAtletas(banco.getListaDeAtletas(campoBusca.getText(), "nome"));
                    } else {
                        if (seletorBuscar.getSelectedItem().toString().equals("Matrícula")){
                            listaDeAtletas = getListaDeTodosAtletas(banco.getListaDeAtletas(campoBusca.getText(), "matricula"));
                        } else{
                            listaDeAtletas = getListaDeTodosAtletas(banco.getListaDeAtletas(campoBusca.getText(), "rg"));
                        }
                    }
                }
            } else{
                if (campoBusca.getText().equals("Pesquisar atleta")){
                    listaDeAtletas = banco.getListaDeAtletas(listaDeCursos.get(seletorCurso.getSelectedIndex() - 1), "curso");
                } else{
                    if (seletorBuscar.getSelectedItem().toString().equals("Nome")){
                        listaDeAtletas = banco.getListaDeAtletas(campoBusca.getText(), "nome", listaDeCursos.get(seletorCurso.getSelectedIndex() - 1));
                    } else {
                        if (seletorBuscar.getSelectedItem().toString().equals("Matrícula")){
                            listaDeAtletas = banco.getListaDeAtletas(campoBusca.getText(), "matricula", listaDeCursos.get(seletorCurso.getSelectedIndex() - 1));
                        } else{
                            listaDeAtletas = banco.getListaDeAtletas(campoBusca.getText(), "rg", listaDeCursos.get(seletorCurso.getSelectedIndex() - 1));
                        }
                    }
                }
                
            }

        } catch (SQLException ex){
            listaDeAtletas = new ArrayList<Integer>(0);
            ex.printStackTrace();
        }
        tabelaAtletas.setModel(modeloTabelaAtletas(listaDeAtletas));
        
        tabelaAtletas.getColumnModel().getColumn(0).setMinWidth(40);
        tabelaAtletas.getColumnModel().getColumn(0).setMaxWidth(40);
        tabelaAtletas.getColumnModel().getColumn(1).setMinWidth(366);
        tabelaAtletas.getColumnModel().getColumn(2).setMinWidth(90);
        tabelaAtletas.getColumnModel().getColumn(2).setPreferredWidth(90);
        tabelaAtletas.getColumnModel().getColumn(3).setMinWidth(90);
        tabelaAtletas.getColumnModel().getColumn(3).setPreferredWidth(90);
        tabelaAtletas.getColumnModel().getColumn(4).setMinWidth(100);
        tabelaAtletas.getColumnModel().getColumn(4).setMaxWidth(100);
        tabelaAtletas.getColumnModel().getColumn(5).setMinWidth(66);
        tabelaAtletas.getColumnModel().getColumn(5).setPreferredWidth(66);

        tabelaAtletas.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoCancelar;
    private javax.swing.JButton botaoGerenciar;
    private javax.swing.JButton botaoPesquisar;
    private javax.swing.JTextField campoBusca;
    private javax.swing.JLabel labelSelecione;
    private javax.swing.JScrollPane scrollTabelaAtletas;
    private javax.swing.JComboBox seletorBuscar;
    private javax.swing.JComboBox seletorCurso;
    private javax.swing.JTable tabelaAtletas;
    // End of variables declaration//GEN-END:variables
}
